import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
import { openBluetoothAdapterPeripheral } from "../../../utils/bluetooth";
const app = getApp();
import util from "../../../utils/util";
import { Index } from '../../../apis/index';
const API = new Index();
const {
  baseUrl,
  yundianUrl
} = require("../../../config");
let computeOrderCostTime = null;
let computeOrderQueryTime = null;
WXPage({
  data: {
    tradeNo: '',
    orderInfo: {},
    statusMap: {
      1: '等待下单',
      2: '租借中...',
      3: '已撤销',
      4: '交易失败',
      5: '已归还',
      6: '支付超时',
      7: '待守约',
      8: '已恢复',
      10: '已删除',
      11: '退款'
    },
    computeOrderQueryTimeNum: 0,
    navigationbarHeight: 60,
    isFinish: false,
    showAd: 1,
    orderUserTime: '',
    hms: '00:00:00',
    hmscn: '00小时00分钟00秒',
    imageUrl: `${app.globalData.imageUrl}`
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("订单详情", options.tradeNo);
    this.setData({
      tradeNo: options.tradeNo,
      showAd: wx.getStorageSync("showAd")
    });
    this.getOrderList();
    // if (options.state && Number(options.state) === 5) {
    //   computeOrderQueryTime = setInterval(ev => {
    //     if(this.data.orderInfo.state === 2) this.getOrderList()
    //     else clearInterval(computeOrderQueryTime)
    //     this.data.computeOrderQueryTime += 1
    //     if (this.data.computeOrderQueryTime > 10) clearInterval(computeOrderQueryTime)
    //   }, 1800)
    // }
  },

  onHide: function () {
    clearInterval(computeOrderCostTime);
    clearInterval(computeOrderQueryTime);
  },
  onUnload: function () {
    clearInterval(computeOrderCostTime);
    clearInterval(computeOrderQueryTime);
  },
  formatTimeMinute(timeAt) {
    return util.formatTime(new Date(timeAt * 1000));
  },
  // 获取订单详情
  getOrderList: function () {
    API.GetOrderInfo({
      "tradeNo": this.data.tradeNo
    }).then(res => {
      let {h, m, s} = util.secondToTime(res.result.useTime)
      let num = `${h}:${m}:${s}`
      let numcn = `${h}时${m}分${s}秒`
      console.log('订单详情', num, numcn)
      this.setData({ 
        orderInfo: res.result,
        hms: num,
        hmscn: numcn
       })
      this.computeOrderCost();
    });
  },
  // 计算订单时长与费用
  async computeOrderCost() {
    let item = this.data.orderInfo
    // 获取此订单的价格详情
    let priceInfo = {}
    await API.GetPriceDetail({ "productId": this.data.orderInfo.productId }).then(res => {
      priceInfo = res.result
      this.setData({ priceInfo: priceInfo }) 
    })
    let orderUserTime = ''
    if (item.state === 2) {
      var timestamp = Date.parse(new Date());  
      timestamp = timestamp / 1000;
      item.useTimeNum = util.formatSecondsTimeNum(parseInt(timestamp) - parseInt(item.beginAt))
      orderUserTime = util.formatSeconds(parseInt(timestamp) - parseInt(item.beginAt))
      this.setData({ orderUserTime: orderUserTime })
    } else if (item.state === 5 || item.state === 3 ) {
      item.useTimeNum = util.formatSecondsTimeNum(parseInt(item.endAt) - parseInt(item.beginAt))
      orderUserTime = util.formatSeconds(parseInt(item.endAt) - parseInt(item.beginAt))
      this.setData({ orderUserTime: orderUserTime })
    }
    this.setData({orderInfo: item})
    clearInterval(computeOrderCostTime)
    // if (item.state === 2) computeOrderCostTime = setInterval(ev => this.computeOrderCost(), 1000)
  },

  // 蓝牙通知
  openBluetoothAdapterPeripheral(targetPowerMinute) {
    openBluetoothAdapterPeripheral({
      bluetoothMac: app.globalData.bluetoothMac,
      powerMinute: targetPowerMinute,
      success: res => {
        console.log('startAdvertising', res);
      }
    });
  },
  // 结束订单，结束使用
  closeOrder: function (ev) {
    let orderInfo = this.data.orderInfo;
    let loginInfo = wx.getStorageSync('login_key');
    wx.showModal({
      title: '小电温馨提示',
      content: '安全用电提醒：充电完毕后，请记得切断电源，将充电线放回方盒。它安全、您安心！充一次、美一次!',
      cancelText: '继续使用',
      confirmText: '立即归还',
      cancelColor: '#666',
      confirmColor: '#00A49AFF',
      success: res => {
        if (!res.confirm) return;
        let param = {
          "deviceSn": orderInfo.deviceSn,
          "productId": orderInfo.productId,
          "openid": loginInfo.openid,
          "tradeNo": orderInfo.tradeNo
        };
        API.closeOrder(param).then(res => {
          if (app.globalData.bluetoothMac) this.openBluetoothAdapterPeripheral(1);
          this.getOrderList();
        });
      }
    });
  },
  // 订单异常
  toRepairs(ev) {
    let {
      deviceSn,
      tradeNo
    } = ev.mark;
    wx.navigateTo({
      url: `/pages/report/report?deviceSn=${deviceSn}&tradeNo=${tradeNo}`
    });
  },
  // 结束使用
  onEnd() {
    console.log('------结束使用------');
    wx.navigateTo({
      url: '/pages/order/success/success'
    });
  },
  // 扫码使用
  scan() {
    wx.scanCode({
      scanType: ['qrCode'],
      success: res => {
        console.log('scanCode', res)

        var result = res.result;
        let q = decodeURIComponent(result);
        app.globalData.deviceSn = util.getQueryString(q, "dev");
        // let pcl = util.getQueryString(q, "pcl");
        // if (q.includes('yundian') || pcl === '10041') {
        //   app.globalData.apiUrl = yundianUrl ? yundianUrl : 'https://gmzfb.cnman.cn/v1/wx/';
        //   app.globalData.isZm = false;
        // } else if (q.includes('blue.chinaman.ink')) {
        //   // 二代线
        //   app.globalData.apiUrl = baseUrl ? baseUrl : 'https://zmapi.cnman.cn/v1/wx/';
        //   app.globalData.isBlue = true;
        // } else {
        //   app.globalData.apiUrl = baseUrl ? baseUrl : 'https://zmapi.cnman.cn/v1/wx/';
        // }
        wx.redirectTo({
          url: '/pages/padline/padline'
        });
      }
    });
  },
  // 复制
  copy(ev) {
    // wx.setClipboardData({
    //   data: ev.mark.tradeNo,
    //   success(res) {
    //     wx.getClipboardData({
    //       success(res) {
    //         console.log(res.data); // data
    //       }
    //     });
    //   }
    // });
  },

  toFZAPP: function () {
    // wx.reportEvent("yd_order_complete_cp", {});
    wx.navigateTo({
      url: '/pages/webview/webview'
    });
  }
});
